package cn.itcast.wushangxiantu.Activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

import cn.itcast.wushangxiantu.BaseAdapter.ZhanShanYuLanAdatper;
import cn.itcast.wushangxiantu.UserData.User;
import cn.itcast.wushangxiantu.UserData.UserZhanshan;
import cn.itcast.wushangxiantu.UserData.ZhanShanYulan;
import cn.itcast.wushangxiantu.MessageEvent;
import cn.itcast.wushangxiantu.OkhttpUtil;
import cn.itcast.wushangxiantu.R;
import cn.itcast.wushangxiantu.ToastUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ZhanShan extends AppCompatActivity implements View.OnClickListener {

    private TextView tvZhanshan1;
    private TextView tvZhanshan2;
    private TextView tvZhanshan3;
    private TextView tvZhanshan4;
    private TextView tvZhanshan5;
    private TextView tvShouYi;
    private TextView tvNumber;
    private TextView tvTime;

    private UserZhanshan user;
    private ZhanShanYulan yulan;
    private TextView tvJinRu;
    private Spinner spDJ;
    private Spinner spPz;
    private ListView lv;
    private ZhanShanYuLanAdatper adatper;
    private AnimationDrawable animationDrawable;
    int Num = 4;
    private ImageView iv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zhan_shan);
        initView();
    }

    private void initView() {
        tvZhanshan1 = (TextView) findViewById(R.id.tvZhanshan1);
        tvZhanshan2 = (TextView) findViewById(R.id.tvZhanshan2);
        tvZhanshan3 = (TextView) findViewById(R.id.tvZhanshan3);
        tvZhanshan4 = (TextView) findViewById(R.id.tvZhanshan4);
        tvZhanshan5 = (TextView) findViewById(R.id.tvZhanshan5);
        tvShouYi = (TextView) findViewById(R.id.tvShouYi);
        tvNumber = (TextView) findViewById(R.id.tvNumber);
        tvTime = (TextView) findViewById(R.id.tvTime);

        tvZhanshan1.setOnClickListener(this);
        tvZhanshan2.setOnClickListener(this);
        tvZhanshan3.setOnClickListener(this);
        tvZhanshan4.setOnClickListener(this);
        tvZhanshan5.setOnClickListener(this);
        tvJinRu = (TextView) findViewById(R.id.tvJinRu);
        tvJinRu.setOnClickListener(this);
        iv = (ImageView) findViewById(R.id.iv);
        spDJ = (Spinner) findViewById(R.id.spDJ);
        spPz = (Spinner) findViewById(R.id.spPz);
        lv = (ListView) findViewById(R.id.lv);
        if (animationDrawable == null) {
            animationDrawable = (AnimationDrawable) iv.getBackground();
        }
        if (!animationDrawable.isRunning()) {
            animationDrawable.start();
        } else {
            iv.setVisibility(View.INVISIBLE);
            animationDrawable.stop();
        }
        getZhanShanUserData();
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String content = yulan.getZhanshan().get(i).getDj() + yulan.getZhanshan().get(i).getPz() + yulan.getZhanshan().get(i).getId() + "号山\n";
                content += "编号：" + yulan.getZhanshan().get(i).getId() + "\n";
                content += "收益：" + yulan.getZhanshan().get(i).getJl() + "/h\n";
                if (yulan.getZhanshan().get(i).getUsername().trim().equals("") || yulan.getZhanshan().get(i).getUsername().trim().equals("null")) {
                    content += "拥有者：空\n";
                } else {
                    content += "拥有者：" + yulan.getZhanshan().get(i).getUsername() + "\n";
                }
                content += "战力：" + yulan.getZhanshan().get(i).getBili() + "%";
                GeneralDialog("山地详情", content, yulan.getZhanshan().get(i).getId());
            }
        });

    }

    private void getZhanShanUserData() {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userNumber=" + Login.getUser().getUsernumber() + "&need=ZhanShanData", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("ZhanShanUser1", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("ZhanShanUser2", src);
                UserZhanshan user =null;
                try {
                    user = new Gson().fromJson(src, UserZhanshan.class);
                }catch (Exception e){

                }
                Message message = new Message();
                message.obj = user;
                message.what = 1;
                handler.sendMessage(message);
            }
        });

    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            if (message.what == 1) {//修改基本信息
                user = (UserZhanshan) message.obj;
                if (null!=user){
                    tvNumber.setText("今日剩余占领次数:" + user.getZsnumber());
                    if (user.getTime() > 60) {
                        tvTime.setText("占山次数刷新:" + (user.getTime() / 60) + "小时后");
                    } else {
                        tvTime.setText("占山次数刷新:" + user.getTime() + "分钟后");
                    }
                    tvShouYi.setText("总收益：" + (user.getZhanshan().get(0).getJl() + user.getZhanshan().get(1).getJl() + user.getZhanshan().get(2).getJl() + user.getZhanshan().get(3).getJl() + user.getZhanshan().get(4).getJl()) + "/h");
                    if (user.getZhanshan().get(0).getId() != 0) {
                        tvZhanshan1.setText(user.getZhanshan().get(0).getDj() + user.getZhanshan().get(0).getPz() + user.getZhanshan().get(0).getId() + "号山");
                    } else {
                        tvZhanshan1.setText("【空】");
                    }
                    if (user.getZhanshan().get(1).getId() != 0) {
                        tvZhanshan2.setText(user.getZhanshan().get(1).getDj() + user.getZhanshan().get(1).getPz() + user.getZhanshan().get(1).getId() + "号山");
                    } else {
                        tvZhanshan2.setText("【空】");
                    }
                    if (user.getZhanshan().get(2).getId() != 0) {
                        tvZhanshan3.setText(user.getZhanshan().get(2).getDj() + user.getZhanshan().get(2).getPz() + user.getZhanshan().get(2).getId() + "号山");
                    } else {
                        tvZhanshan3.setText("【空】");
                    }
                    if (user.getZhanshan().get(3).getId() != 0) {
                        tvZhanshan4.setText(user.getZhanshan().get(3).getDj() + user.getZhanshan().get(3).getPz() + user.getZhanshan().get(3).getId() + "号山");
                    } else {
                        tvZhanshan4.setText("【空】");
                    }
                    if (user.getZhanshan().get(4).getId() != 0) {
                        tvZhanshan5.setText(user.getZhanshan().get(4).getDj() + user.getZhanshan().get(4).getPz() + user.getZhanshan().get(4).getId() + "号山");
                    } else {
                        tvZhanshan5.setText("【空】");
                    }
                }else {
                    ToastUtil.toast(ZhanShan.this,"服务器炸了");
                }
            } else if (message.what == 2) {//修改listview
                yulan = (ZhanShanYulan) message.obj;
                if (null!=yulan){
                    if (yulan.getStw() == null) {
                        if (adatper == null) {
                            adatper = new ZhanShanYuLanAdatper(ZhanShan.this);
                        }
                        adatper.setZhanShanYulan(yulan);
                        lv.setAdapter(adatper);
                    } else {
                        ToastUtil.toast(ZhanShan.this, yulan.getStw());
                    }
                }else {
                    ToastUtil.toast(ZhanShan.this,"服务器不行了");
                }
            } else if (message.what == 3) {//放弃
                User xiaoxi = (User) message.obj;
                if (null!=xiaoxi){
                    ToastUtil.toast(ZhanShan.this, xiaoxi.getStw());
                    EventBus.getDefault().post(new MessageEvent("YouXiang"));
                }else{
                    ToastUtil.toast(ZhanShan.this,"服务器不行了");
                }
            } else if (message.what == 4) {//占山
                User xiaoxi = (User) message.obj;
                if (null!=xiaoxi){
                    ToastUtil.toast(ZhanShan.this, xiaoxi.getStw());
                }else{
                    ToastUtil.toast(ZhanShan.this,"服务器不行了");
                }
            }
            if (message.what == 3 || message.what == 4) {
                getZhanShanUserData();
            }
            if (message.what != 2) {
                getYuLan(Num);
            }
            iv.setVisibility(View.INVISIBLE);
            animationDrawable.stop();

            return false;
        }
    });


    @Override
    public void onClick(View view) {
        if (null==user){
            ToastUtil.toast(ZhanShan.this,"异常错误");
            return;
        }
        switch (view.getId()) {
            case R.id.tvZhanshan1:
                if (user.getZhanshan().get(0).getId() != 0) {
                    String content = user.getZhanshan().get(0).getDj() + user.getZhanshan().get(0).getPz() + user.getZhanshan().get(0).getId() + "号山\n";
                    content += "编号：" + user.getZhanshan().get(0).getId() + "\n";
                    content += "收益：" + user.getZhanshan().get(0).getJl() + "/h\n";
                    content += "上次收益时间：" + user.getZhanshan().get(0).getTime() + "\n";
                    content += "战力：" + user.getZhanshan().get(0).getBili() + "%";
                    GeneralDialogFangQi("山地详情", content, user.getZhanshan().get(0).getId(), 1);
                }
                break;
            case R.id.tvZhanshan2:
                if (user.getZhanshan().get(1).getId() != 0) {
                    String content = user.getZhanshan().get(1).getDj() + user.getZhanshan().get(1).getPz() + user.getZhanshan().get(1).getId() + "号山\n";
                    content += "编号：" + user.getZhanshan().get(1).getId() + "\n";
                    content += "收益：" + user.getZhanshan().get(1).getJl() + "/h\n";
                    content += "上次收益时间：" + user.getZhanshan().get(1).getTime() + "\n";
                    content += "战力：" + user.getZhanshan().get(1).getBili() + "%";
                    GeneralDialogFangQi("山地详情", content, user.getZhanshan().get(1).getId(), 2);
                }
                break;
            case R.id.tvZhanshan3:
                if (user.getZhanshan().get(2).getId() != 0) {
                    String content = user.getZhanshan().get(2).getDj() + user.getZhanshan().get(2).getPz() + user.getZhanshan().get(2).getId() + "号山\n";
                    content += "编号：" + user.getZhanshan().get(2).getId() + "\n";
                    content += "收益：" + user.getZhanshan().get(2).getJl() + "/h\n";
                    content += "上次收益时间：" + user.getZhanshan().get(2).getTime() + "\n";
                    content += "战力：" + user.getZhanshan().get(2).getBili() + "%";
                    GeneralDialogFangQi("山地详情", content, user.getZhanshan().get(2).getId(), 3);
                }
                break;
            case R.id.tvZhanshan4:
                if (user.getZhanshan().get(3).getId() != 0) {
                    String content = user.getZhanshan().get(3).getDj() + user.getZhanshan().get(3).getPz() + user.getZhanshan().get(3).getId() + "号山\n";
                    content += "编号：" + user.getZhanshan().get(3).getId() + "\n";
                    content += "收益：" + user.getZhanshan().get(3).getJl() + "/h\n";
                    content += "上次收益时间：" + user.getZhanshan().get(3).getTime() + "\n";
                    content += "战力：" + user.getZhanshan().get(4).getBili() + "%";
                    GeneralDialogFangQi("山地详情", content, user.getZhanshan().get(3).getId(), 4);
                }
                break;
            case R.id.tvZhanshan5:
                if (user.getZhanshan().get(4).getId() != 0) {
                    String content = user.getZhanshan().get(4).getDj() + user.getZhanshan().get(4).getPz() + user.getZhanshan().get(4).getId() + "号山\n";
                    content += "编号：" + user.getZhanshan().get(4).getId() + "\n";
                    content += "收益：" + user.getZhanshan().get(4).getJl() + "/h\n";
                    content += "上次收益时间：" + user.getZhanshan().get(4).getTime() + "\n";
                    content += "战力：" + user.getZhanshan().get(4).getBili() + "%";
                    GeneralDialogFangQi("山地详情", content, user.getZhanshan().get(4).getId(), 5);
                }
                break;
            case R.id.tvJinRu:
                if (!animationDrawable.isRunning()){
                    animationDrawable.start();
                }else {
                    iv.setVisibility(View.INVISIBLE);
                    animationDrawable.stop();
                }
                int num = (spDJ.getSelectedItemPosition() + 1) * 2 - 1 + (spPz.getSelectedItemPosition() );
                Num = num * 4;
                getYuLan(Num);

                break;
        }
    }

    private void getYuLan(final int num) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=zhanshanyulan" + "&jl=" + num, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("yulan1", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("yulan2", src);
                ZhanShanYulan yulan = null;
                try {
                    yulan = new Gson().fromJson(src, ZhanShanYulan.class);
                }catch (Exception e){

                }
                Message message = new Message();
                message.obj = yulan;
                message.what = 2;
                handler.sendMessage(message);
            }
        });

    }

    public void GeneralDialogFangQi(String head, String content, final int id, final int wz) {
        /**
         * 普通对话框
         * 1标题
         * 2内容
         */
        AlertDialog dialog;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(head);
        builder.setMessage(content);
        builder.setNeutralButton("领取收益", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                getShouyi(id, Login.getUser().getUsernumber());
            }
        });
        builder.setPositiveButton("放弃山地", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                GeneralDialog("放弃山地","确定放弃当前山地吗？",id,wz);
                dialogInterface.dismiss();
            }
        });
        dialog = builder.create();
        dialog.show();
    }
    public void GeneralDialog(String head, String content, final int id, final int wz) {
        /**
         * 普通对话框
         * 1标题
         * 2内容
         */
        AlertDialog dialog;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(head);
        builder.setMessage(content);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                getFangqi(id, wz);
                dialogInterface.dismiss();
            }
        });
        dialog = builder.create();
        dialog.show();
    }
    private void getFangqi(int id, int wz) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=fangqi" + "&id=" + id + "&userNumber=" + Login.getUser().getUsernumber() + "&wz=" + wz, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("fangqi2", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("fangqi1", src);
                User user = null;
                try {
                    user = new Gson().fromJson(src, User.class);
                }catch (Exception e){

                }
                Message message = new Message();
                message.obj = user;
                message.what = 3;
                handler.sendMessage(message);
            }
        });
    }

    private void getShouyi(int id, String usernumber) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=zhanshanjiangli" + "&id=" + id + "&userNumber=" + usernumber, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("yulan1", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("yulan2", src);
                User user = null;
                try {
                    user = new Gson().fromJson(src, User.class);
                }catch (Exception e){

                }
                Message message = new Message();
                message.obj = user;
                message.what = 3;
                handler.sendMessage(message);
            }
        });
    }

    public void GeneralDialog(String head, String content, final int id) {
        /**
         * 普通对话框
         * 1标题
         * 2内容
         */
        AlertDialog dialog;
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle(head)

                .setMessage(content)
                .setPositiveButton("占领", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        new Thread(){
                            @Override
                            public void run() {
                                try {
                                    sleep(2000);
                                    getZhanLing(id);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }.start();
                        dialogInterface.dismiss();
                    }
                });
        dialog = builder.create();
        dialog.show();
    }

    private void getZhanLing(int id) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "&need=zhanling" + "&id=" + id + "&userNumber=" + Login.getUser().getUsernumber() + "&name=" + Login.getUser().getName(), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("yulan1", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("zhanling", src);
                User user =null;
                try {
                    user = new Gson().fromJson(src, User.class);
                }catch (Exception e){

                }
                Message message = new Message();
                message.obj = user;
                message.what = 4;
                handler.sendMessage(message);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
        EventBus.getDefault().unregister(this);
        if (animationDrawable.isRunning()){
            animationDrawable.stop();
        }
        iv.clearAnimation();
    }
}
